package com.ncloud.crm.service.impl;

import java.util.*;

import com.ncloud.param.service.SequenceService;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ncloud.common.enmus.ResultEnum;
import com.ncloud.common.exception.UserException;
import com.ncloud.crm.common.Constant;
import com.ncloud.crm.entity.BsAttr;
import com.ncloud.crm.entity.order.OrderAttr;
import com.ncloud.crm.mapper.BsAttrMapper;
import com.ncloud.crm.mapper.OrderAttrMapper;
import com.ncloud.crm.service.OrderAttrService;
import com.ncloud.crm.utils.DateUtils;
import com.ncloud.crm.utils.ItemInfoUtils;
import com.ncloud.param.service.TagService;

@Service
public class OrderAttrServiceImpl implements OrderAttrService {
	
	private static final Logger logger = LogManager.getLogger(OrderAttrServiceImpl.class);
	
	@Autowired
	private OrderAttrMapper orderAttrMapper;
	@Autowired
	private BsAttrMapper bsAttrMapper;
	@Reference
	private SequenceService sequenceService;
	@Reference
	private TagService tagService;

	public JSONArray getId(JSONObject json) {
		if(json==null || !json.containsKey("id")){
			throw new UserException(ResultEnum.PARAM_ERROR);
		}
		List<OrderAttr> orderAttrs = orderAttrMapper.getAttrById(json.getLong("id"),json.getString("attrType"));
		return JSON.parseArray(JSON.toJSONString(orderAttrs));
	}
	
	public List<OrderAttr> getAttrsById(Long instId,String attrType) {
		List<OrderAttr> orderAttrs = orderAttrMapper.getAttrById(instId,attrType);
		return orderAttrs;
	}

	@Override
	public JSONObject getPk(JSONObject json) {
		return null;
	}

	@Override
	public JSONObject insert(JSONObject json) {

		OrderAttr orderAttr = JSON.parseObject(json.toJSONString(),OrderAttr.class);
		try {
			validation(orderAttr);
			orderAttrMapper.insertOrderAttr(orderAttr);
		}catch (RuntimeException e){
			e.printStackTrace();
			throw new UserException(ResultEnum.DATABASE_ERROR);
		}
		return json;
	}
	private void validation(OrderAttr orderAttr){
		if(orderAttr.getAttrId() == null){
			Long id = sequenceService.getSequence("seq_item_id");
			orderAttr.setAttrId(id);
		}
	}
	@Override
	public JSONObject validate(JSONObject json,JSONObject result) {
		JSONObject object = new JSONObject();
		return object;
	}

	@Override
	/*public static String ATTR_TYPE_PROD="0";
	public static String ATTR_TYPE_DISCNT="1";
	public static String ATTR_TYPE_ORDER="2";
	public static String ATTR_TYPE_WORK="3";
	public static String ATTR_TYPE_CUST="4";*/

	public void geneAttrInfos(JSONObject attr, Long id, String type, JSONArray array,String filter) {
		String currentDataTime = DateUtils.getDateTime();
		/*提取要处理的属性信息*/
		//JSONObject nodeItems = new JSONObject();
		List<String> keys = getAttrInfo(filter);
		/*声明查询条件*/
		BsAttr paramAttr = new BsAttr();
		paramAttr.setAttrType(type);
		paramAttr.setId(id);
		Date date = new Date();
		paramAttr.setBeginDate(date);
		paramAttr.setEndDate(date);
		for (Map.Entry<String, Object> entry : attr.entrySet()) {
			OrderAttr attrNew = new OrderAttr();
			String key = entry.getKey();
			/*处理配置的属性*/
			if(keys.contains(key)){
				/*对金额的属性进行处理*/
				String value = ItemInfoUtils.isMoney(key)?String.valueOf(ItemInfoUtils.getMultiMoney(entry.getValue(),100)):String.valueOf(entry.getValue());
				//nodeItems.put(key,entry.getValue());
				paramAttr.setAttrCode(key);
				BsAttr bsAttrOld = bsAttrMapper.getValidAttrInfo(paramAttr);
				if(bsAttrOld != null){
					OrderAttr attrOld = JSON.parseObject(JSON.toJSONString(bsAttrOld),OrderAttr.class);
					attrOld.setId(id);
					attrOld.setEndDate(DateUtils.parseDate(currentDataTime));
					attrOld.setModifyTag(Constant.DEL);
											/*保存原来信息*/
					array.add(JSON.parseObject(JSON.toJSONString(bsAttrOld)));
					/*增加一条新信息*/
					attrNew.setId(id);
					attrNew.setModifyTag(Constant.ADD);
					attrNew.setAttrType(type);
					attrNew.setBeginDate(DateUtils.parseDate(currentDataTime));
					attrNew.setEndDate(DateUtils.parseDate(Constant.END_DATE));
					attrNew.setAttrCode(key);
					attrNew.setAttrValue(value);
				}else{
					attrNew.setId(id);
					attrNew.setModifyTag(Constant.ADD);
					attrNew.setAttrType(type);
					attrNew.setBeginDate(DateUtils.parseDate(currentDataTime));
					attrNew.setEndDate(DateUtils.parseDate(Constant.END_DATE));
					attrNew.setAttrCode(key);
					attrNew.setAttrValue(value);
				}
				array.add(JSON.parseObject(JSON.toJSONString(attrNew)));
			}
		}
	}

	public void geneAttrInfosCondition(JSONObject attr, Long id, String type, JSONArray array,String filter) {
		String currentDataTime = DateUtils.getDateTime();
		/*提取要处理的属性信息*/
		//JSONObject nodeItems = new JSONObject();
		List<String> keys = getAttrInfo(filter);
		/*声明查询条件*/
		BsAttr paramAttr = new BsAttr();
		paramAttr.setAttrType(type);
		paramAttr.setId(id);
		Date date = new Date();
		paramAttr.setBeginDate(date);
		paramAttr.setEndDate(date);
		for (Map.Entry<String, Object> entry : attr.entrySet()) {
			OrderAttr attrNew = new OrderAttr();
			String key = entry.getKey();
			/*处理配置的属性*/
			if(keys.contains(key)){
				/*对金额的属性进行处理*/
				String value = ItemInfoUtils.isMoney(key)?String.valueOf(ItemInfoUtils.getMultiMoney(entry.getValue(),100)):String.valueOf(entry.getValue());
				//nodeItems.put(key,entry.getValue());
				paramAttr.setAttrCode(key);
				BsAttr bsAttrOld = bsAttrMapper.getValidAttrInfo(paramAttr);
				if(bsAttrOld == null){
					attrNew.setId(id);
					attrNew.setModifyTag(Constant.ADD);
					attrNew.setAttrType(type);
					attrNew.setBeginDate(DateUtils.parseDate(currentDataTime));
					attrNew.setEndDate(DateUtils.parseDate(Constant.END_DATE));
					attrNew.setAttrCode(key);
					attrNew.setAttrValue(value);
					array.add(JSON.parseObject(JSON.toJSONString(attrNew)));
				}
			}
		}
	}
/*	private List<String> getAttrKeys(String tagCode){
		List<String> list = new ArrayList<String>();
		JSONObject tagParam = new JSONObject();
		tagParam.put("tagCode",tagCode);
		JSONArray tagArray = tagService.getTagInfo(tagParam);
		String tagInfo = tagArray.getJSONObject(0).getString("tagInfo");
		if(tagInfo !=null){
			String[] tagKeys = tagInfo.split(",");
			list = Arrays.asList(tagKeys);
		}
		return list;
	}*/

	/*根据属性获取对应的费用信息*/
	@Override
	public JSONObject getFeeAttrInfo(JSONObject attr,String type,JSONObject target){
		if(target == null) target  = new JSONObject();
		Map<String,String> attrMap = getAttrsMap("item_array_"+type);
		for (Map.Entry<String, Object> entry : attr.entrySet()) {
			String key = entry.getKey();
			if(attrMap.containsKey(key)){
				/*对金额的属性进行处理*/
				String value = ItemInfoUtils.isMoney(key)?String.valueOf(ItemInfoUtils.getMultiMoney(entry.getValue(),100)):String.valueOf(entry.getValue());
				String field = attrMap.get(key);
				target.put(field,value);
			}
		}
		return target;
	}
	private Map<String,String> getAttrsMap(String tagCode){
		Map<String,String> map = new HashMap<String,String>();
		JSONObject tagParam = new JSONObject();
		tagParam.put("tagCode",tagCode);
		JSONArray tagArray = tagService.getTagInfo(tagParam);
		String tagInfo = tagArray.getJSONObject(0).getString("tagInfo");
		if(tagInfo !=null){
			String[] tagKeys = tagInfo.split(",");
			for(String key:tagKeys){
				String[] info = key.split(":");
				if(info.length>1){
					map.put(info[0],info[1]);
				}else{
					map.put(info[0],info[0]);
				}
			}
		}
		return map;
	}
	public String getAttrByKey(Long id, String attrType, String key) {
		String value = "";
		OrderAttr attr = orderAttrMapper.getAttrByKey(id,attrType,key);
		if(attr!=null)
			value= attr.getAttrValue();
		return value;
	}

	public  List<String> getAttrInfo(String tagCode){
		List<String> list = new ArrayList<String>();
		JSONObject tag = tagService.getTagInfoOne(tagCode);
		String tagInfo = tag.getString("tagInfo");
		if(tagInfo !=null){
			String[] tagKeys = tagInfo.split(",");
			list = Arrays.asList(tagKeys);
		}
		return list;
	}
}
